<?php
$aPath = Yii::app()->theme->baseUrl . '/assets/';

$module = Yii::app()->controller->module->id;
$cont = Yii::app()->controller->id;
$action = Yii::app()->controller->action->id;
$isIndex = false;

if( $module == "main" && $cont == "main" && $action == "index" )
{
	$isIndex = true;
}
?>
<dl class="<?php echo $isIndex ? 'selected-content__widget' : 'widget '; ?>">
	<dt>Адреса в других городах</dt>
	<dd>    
		<ul class="<?php echo $isIndex?'':'address-list';?>" id="getRegionAddress">
			<?php
			$regions = Yii::app()->params[ 'regions' ];

			foreach( $regions as $regId => $region )
			{
				$selected = "";
				if( $regId == Yii::app()->getModule( 'main' )->userRegion[ 'id' ] )
				{
					$selected = ' class= "selected" ';
				}
				echo '<li ' . $selected . '><a href="#"><span data-id="' . $region[ 'regionId' ] . '">' . $region[ 'regionTitle' ] . '</span></a></li>';
			}
			?>
		</ul>
	</dd>
</dl>
<script>
	$(function()
	{
		var cAjaxId = false;

		$('ul#getRegionAddress').on("click", "li", function()
		{
			var li = $(this);
			if (li.hasClass("selected"))
				return false;
			if (cAjaxId)
			{
				cAjaxId.abort();
			}
			cAjaxId = $.ajax({
				url: '/main/ajax/getContacts',
				type: 'post',
				data: {regionId: li.find('span').data("id"), mainPage: <?php echo $isIndex ? 'true' : 'false'; ?>},
				success: function(contacts)
				{
					var cities = [
                                            <?php 
                                                foreach( Yii::app()->params['regions'] as $region)
                                                {
                                                    echo "'".$region['genitive']."',";
                                                }
                                            ?>
						//'Москве', 'Санкт-Петербурге', 'Нижнем Новгороде', 'Екатеринбурге', 'Новосибирске', 'Казане'
					];

					contacts = JSON.parse(contacts);
					// console.log( contacts );
					if (contacts.response == 'success')
					{
						if (contacts.data.length > 0)
						{
							$('ul#getRegionAddress>li').removeClass("selected");

							li.addClass("selected");

							var aBlock = $('dl#regionAddresses');

							aBlock.find('dt').html('Адреса ремонта в ' + cities[ li.find('span').data("id") - 1] );
							aBlock = aBlock.find('ul');

							aBlock.html('');

							var cBlock = false;
							var variable;
							for (var key in contacts.data)
							{
								variable = aBlock.is('.address-list') ? '<span>' + contacts.data[key].pageTitle + '</span>' : contacts.data[key].pageTitle;
								aBlock.append($('<li><a class="' + contacts.data[key].metroCss + '" href="/' + contacts.data[key].pageUrl + '">'+variable+'</a></li>'));
							}
						}
					}
					cAjaxId = false;
				}
			});
			return false;
		});
	});
</script>

